import time

from vidgear.gears import CamGear, StreamGear, PiGear
from threading import Thread, Event
from queue import Queue


def thread_trance(channel: Queue, status: Event, streams):

    while not status.is_set():
        lastTime = time.time()
        frame = streams.read()
        if frame is None:
            break
        else:
            channel.put(frame)
            nowTime = time.time()
    streams.stop()


def thread_stream(channel: Queue, status: Event, streamers):

    while not status.is_set():
        try:
            frame = channel.get()
            streamers.stream(frame)
        except:
            break
    status.is_set()
    streamers.terminate()


if __name__ == '__main__':
    taskQueue = Queue(1)
    taskEvent = Event()
    CamOptions = {
        "CAP_PROP_FRAME_WIDTH": 640,
        "CAP_PROP_FRAME_HEIGHT": 480,
        "CAP_PROP_FPS": 30
    }
    stream = CamGear(source=0, logging=True, **CamOptions).start()
    stream_params = {
        "-livestream": True,
        "-vcodec": "h264_omx",
        "-sc_threshold": "499",
        "-f": "flv",
        "-input_framerate": stream.framerate,
        "-audio": ["-f", "alsa", "-i", "plug:hw:2"],
    }
    streamer = StreamGear(output="rtmp://139.155.181.21/live/Cam", **stream_params)
    taskTrance = Thread(target=thread_trance, args=(taskQueue, taskEvent, stream))
    taskStream = Thread(target=thread_stream, args=(taskQueue, taskEvent, streamer))
    taskTrance.setDaemon(True)
    taskStream.setDaemon(True)
    taskTrance.start()
    taskStream.start()
    while True:
        try:
            pass
        except KeyboardInterrupt:
            break
    taskEvent.set()
    taskTrance.join()
    taskStream.join()
